package com.appspot.codelab.docs.server.auth;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * Encapsulates AuthSub Authentication routines.
 */
@SuppressWarnings("serial")
public class AuthenticationManager extends HttpServlet {
  
  private AuthenticationManager() {
  }
  
  /**
   * Determines whether the current user is authenticated.
   */
  public static boolean isAuthenticated() {
    UserService userService = UserServiceFactory.getUserService();
    if (userService.getCurrentUser() != null) {
      return true;
    }
    return false;
  }
  
  /**
   * Automatically guides the user through authentication, redirecting as appropriate.
   * 
   * @param req the HTTP request object
   * @param resp the HTTP response object
   * @throws IOException if a redirect error occurs
   */
  public static void authenticate(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    UserService userService = UserServiceFactory.getUserService();
    if (userService.getCurrentUser() == null) {
      String authUrl = userService.createLoginURL(getFullUrl(req));
      resp.sendRedirect(authUrl);
    }
  }
  
  /**
   * Obtains the full URL for the current request, eliminating
   * the token parameter, if it is present. The token removal isn't
   * required but helps protect the user from by minimizing its
   * visibility.
   * 
   * @param req
   * @return
   */
  @SuppressWarnings("unchecked")
  private static String getFullUrl(HttpServletRequest req) {
    String url = req.getRequestURL().toString();
    String qs = "";
    Enumeration<String> pars = req.getParameterNames();
    while(pars.hasMoreElements()) {
      String name = pars.nextElement();
      if (!name.equals("token")) {
        String value = req.getParameter(name);
        if (value != null) {
          try {
            qs += name + "=" + URLEncoder.encode(value, "UTF-8") + "&";
          } catch (UnsupportedEncodingException e) {
          }
        }
      }
    }
    if (!qs.equals("")) {
      url += "?" + qs;
    }
    return url;
  }
  
}
